package com.teamin.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.core.util.StringUtils;
import com.teamin.config.ErrorCode;
import com.teamin.config.OSSUtil;
import com.teamin.dto.FileDTO;
import com.teamin.dto.NetDiskFolderDTO;
import com.teamin.dto.UploadFIleListDTO;
import com.teamin.entity.NetDisk;
import com.teamin.mapper.NetDiskMapper;
import com.teamin.service.INetDiskService;
import com.teamin.service.UserService;
import com.teamin.service.impl.FileServiceImpl;
import com.teamin.utils.SerializationUtils;
import com.teamin.web.exception.GlobalErrorInfoException;
import com.teamin.web.model.ErrorInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: yangrui
 * @Description: user folder controller
 * @Date: 下午3:48 2017/11/20
 */
@Api(description = "网盘api-1", tags = "网盘1")
@RestController
@RequestMapping(value = "/circle/netdisk")
public class UserFolderController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private INetDiskService netDiskService;

    @Autowired
    private UserService userService;

    @Autowired
    private FileServiceImpl fileService;

    @Autowired
    NetDiskMapper netDiskMapper;

    @Autowired
    OSSUtil ossUtil;

    /**
     * @Author: yangrui
     * @Description: 新建文件夹
     * @Date: 下午3:51 2017/11/20
     */
    @ApiOperation(value = "新建文件夹")
    @PostMapping(value = "/{circleId:\\d+}/saveFolder")
    public NetDisk saveFolder(@ApiParam(value = "圈子ID", required = true) @PathVariable Integer circleId,
                              @RequestAttribute("loginUserId") Long loginUserId,
                              @Valid NetDiskFolderDTO netDiskFolderDTO,
                              BindingResult result) throws GlobalErrorInfoException {
        if (result.hasFieldErrors()) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST.value(), result.getFieldError().getDefaultMessage()));
        }
        // 不属于圈子
        if (!userService.userInCircle(loginUserId, Long.valueOf(circleId))) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
        }
        // 圈子结点不存在
        if (0 != netDiskFolderDTO.getNode()) {
            Long id = netDiskMapper.exist(netDiskFolderDTO.getNode(), circleId);
            if (id == null) {
                throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
            }
        }
        // 文件夹名称存在
        Long id = netDiskMapper.fileNameExist(circleId, netDiskFolderDTO.getFolderName(), netDiskFolderDTO.getNode());
        if (id != null) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.FILE_NAME_EXIST));
        }
        try {
            NetDisk netDisk = new NetDisk();
            netDisk.setCircleid(circleId);
            netDisk.setCreateUserid(loginUserId);
            netDisk.setFileName(netDiskFolderDTO.getFolderName());
            netDisk.setParentId(Long.valueOf(netDiskFolderDTO.getNode()));
            netDisk.setIsFile(0);
            netDisk.setIsdelete(0);
            netDiskService.save(netDisk);

            return netDisk;
        } catch (RuntimeException ex) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.DATA_FAIL));
        }
    }

    /**
     * @Author: yangrui
     * @Description: 获取来自任务附件文件
     * @Date: 下午4:03 2017/11/20
     */
    @ApiOperation(value = "获取来自任务附件文件")
    @GetMapping(value = "/listFiles")
    public List<NetDisk> listFiles(@ApiParam(value = "圈子ID", required = true) @RequestParam Integer circleId, @RequestAttribute("loginUserId") Long loginUserId) throws GlobalErrorInfoException {
        // 不属于圈子
        if (!userService.userInCircle(loginUserId, Long.valueOf(circleId))) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
        }
        List<NetDisk> netDisks;
        try {
            netDisks = netDiskService.listFilesByAnnex(circleId);
            if (netDisks != null && netDisks.size() > 0) {
                netDisks.stream().forEach(object -> {
                    NetDisk vo = object;
                    if (vo.getCreateUserid().equals(loginUserId)) {
                        vo.setSelf(0);
                    } else {
                        vo.setSelf(1);
                    }
                });
            }
        } catch (RuntimeException ex) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.DATA_FAIL));
        }
        return netDisks;
    }

    /**
     * @Author: yangrui
     * @Description: 搜索
     * @Date: 下午4:16 2017/11/20
     */
    @ApiOperation(value = "搜索")
    @GetMapping(value = "/findByFolderName")
    public List<NetDisk> findFolders(@RequestAttribute("loginUserId") Long loginUserId, @ApiParam(value = "圈子ID", required = true) @RequestParam Integer circleId, @ApiParam(value = "文件名称", required = true) @RequestParam String folderName, @ApiParam(value = "当前目录ID", required = true) @RequestParam Long id) throws GlobalErrorInfoException {
        // 不属于圈子
        if (!userService.userInCircle(loginUserId, Long.valueOf(circleId))) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
        }
        List<NetDisk> netDisks;
        try {
            NetDisk netDisk = new NetDisk();
            netDisk.setCircleid(circleId);
            netDisk.setScreen(folderName);
            netDisk.setId(id);
            netDisks = netDiskService.findFiles(netDisk);
        } catch (RuntimeException ex) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.DATA_FAIL));
        }
        return netDisks;
    }

    /**
     * @Author: yangrui
     * @Description: 获取根目录
     * @Date: 下午4:21 2017/11/20
     */
    @ApiOperation(value = "获取根目录")
    @GetMapping(value = "/findByFolderId")
    public List<NetDisk> find(@RequestAttribute("loginUserId") Long loginUserId, @ApiParam(value = "圈子ID", required = true) @RequestParam Integer circleId, @ApiParam(value = "node节点，根目录node为0", required = true) @RequestParam Long folderId) throws GlobalErrorInfoException {
        // 不属于圈子
        if (!userService.userInCircle(loginUserId, Long.valueOf(circleId))) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
        }
        NetDisk netDisk = new NetDisk();
        netDisk.setCircleid(circleId);
        netDisk.setId(folderId);
        List<NetDisk> list = netDiskService.findChild(netDisk);
        if (list != null && list.size() > 0) {
            list.stream().forEach(object -> {
                NetDisk vo = object;
                if (vo.getIsFile() == 1 && !vo.getUuid().equals("-1")) {
                    try {
                        vo.setFileUrl(ossUtil.getUrlByKey(vo.getUuid()));
                    } catch (Exception e) {
                        logger.error("uuid获取oss图片url失败");
                    }
                }
            });
        }
        return list;
    }

    /**
     * 新增文件并返回URL 地址
     *
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/file")
    public JSONArray addFile(@RequestAttribute("loginUserId") Long loginUserId, @ApiParam(value = "圈子ID", required = true) @RequestParam Integer fkCircleId, @ApiParam(value = "node节点，根目录node为0", required = true) @RequestParam Long folderId, String fileList) throws Exception {
        logger.debug("oole /circle/netdisk/file fileList {}", fileList);
        List<FileDTO> fileDTOList = SerializationUtils.getListFromJsonArrStr(fileList, FileDTO.class);
        if (fileDTOList != null && fileDTOList.size() > 0) {
            JSONArray jsonArray = new JSONArray();
            for (FileDTO fileDTO : fileDTOList) {
                //文件名的校验
                if (StringUtils.isNullOrEmpty(fileDTO.getFileName()) || fileDTO.getFileName().length() > 100 || StringUtils.isNullOrEmpty(fileDTO.getFileSize() + "")) {
                    throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FILE_NAME_ERROR));
                }
                jsonArray.add(fileService.getNetDiskPostUrl(loginUserId, fkCircleId, folderId, fileDTO.getFileName(), fileDTO.getFileSize()));
            }
            return jsonArray;
        }
        return null;
    }

    /**
     * @Author: yangrui
     * @Description: 删除
     * @Date: 下午6:23 2017/11/21
     */
    @ApiOperation(value = "删除")
    @PostMapping(value = "/removeFolder")
    public void removeFolder(@RequestAttribute("loginUserId") Long loginUserId, @ApiParam(value = "圈子ID", required = true) @RequestParam Integer circleId, @ApiParam(value = "删除的文件(夹)ID集合,逗号隔开", required = true) @RequestParam String ids) throws GlobalErrorInfoException {
        // 不属于圈子
        if (!userService.userInCircle(loginUserId, Long.valueOf(circleId))) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
        }
        String[] strarr = ids.split(",");
        List list = Arrays.asList(strarr);
        netDiskService.rm(loginUserId, list);
    }

    /**
     * @Author: yangrui
     * @Description: 获取图片url
     * @Date: 下午9:17 2017/11/21
     */
    @ApiOperation(value = "获取文件url")
    @GetMapping(value = "/getFiles")
    public List<String> getFiles(@ApiParam(value = "ali oss key") @RequestParam String keys) {
        List<String> list = new ArrayList<>();
        String[] strArr = keys.split(",");
        for (String str : strArr) {
            try {
                list.add(ossUtil.getUrlByKey(str));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    /**
     * 新增文件并返回URL 地址
     *
     * @return
     * @throws Exception
     */
    /*@PostMapping(value = "/files")
    public UploadFIleListDTO addFiles(@RequestAttribute("loginUserId") Long loginUserId,
                                      @ApiParam(value = "圈子ID", required = true) @RequestParam Integer fkCircleId,
                                      @Valid UploadFIleListDTO uploadFIleListDTO) throws Exception {
        fileService.saveFile(loginUserId, fkCircleId, uploadFIleListDTO);

        return uploadFIleListDTO;
    }*/
}
